package com.scau.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.scau.dao.BaseDao;
import com.scau.dao.IEmployeeDao;
import com.scau.vo.Employee;
import com.scau.vo.EmployeeCategory;

/**
 * @author Jinglun
 * @create 2017年4月20日
 */
public class EmployeeDaoImpl extends BaseDao implements IEmployeeDao {

	private Session session = null;
	private Transaction tx = null;
	private String hql = "";
	
	@Override
	public boolean saveEmployee(Employee employee) {
		session = getSession();
		tx = session.beginTransaction();
		
		hql = "from Employee em where em.name ='" + employee.getName() +"'";
		Employee exist = (Employee) session.createQuery(hql).uniqueResult();
		
		if(exist != null) {
			tx.commit();
			session.close();
			return false;
		} else {
			// 前端json返回的type里保存了员工类型的id!!
			Integer ecId = Integer.parseInt(employee.getType());
			EmployeeCategory ec = (EmployeeCategory)session.get(EmployeeCategory.class, ecId);
			employee.setEmployeeCategory(ec);
			
			session.save(employee);
			tx.commit();
			session.close();
			return true;
		}
	}

	@Override
	public boolean deleteEmployee(int id) {
		session = getSession();
		tx = session.beginTransaction();
		
		Employee employee = (Employee) session.get(Employee.class, id);
		session.delete(employee);
		
		tx.commit();
		session.close();
		return true;
		
	}

	@Override
	public List<Employee> listEmployee() {
		session = getSession();
		tx = session.beginTransaction();
		
		hql = "from Employee empl";
		Query query = session.createQuery(hql);
		List<Employee> listEmployee = query.list();
		
		session.close();
		return listEmployee;
	}

	@Override
	public boolean updateEmployee(Employee employee) {
		session = getSession();
		tx = session.beginTransaction();
		
		Employee upEmpl = (Employee) session.get(Employee.class, employee.getId());
		
		upEmpl.setName(employee.getName());
		upEmpl.setPhone(employee.getPhone());
		upEmpl.setSex(employee.getSex());
		upEmpl.setSalary(employee.getSalary());
		upEmpl.setRemark(employee.getRemark());
		upEmpl.setGmtModified(employee.getGmtModified());
		
		Integer emplCateId = Integer.parseInt(employee.getType());
		EmployeeCategory ec = (EmployeeCategory)session.get(EmployeeCategory.class, emplCateId);
		upEmpl.setEmployeeCategory(ec);
		upEmpl.setType(ec.getName());
		
		tx.commit();
		session.close();
		return true;
	}

}
